package com.iscas.lndicatormonitor.utils;

import com.iscas.lndicatormonitor.domain.Loginattempt;
import com.iscas.lndicatormonitor.service.LoginattemptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class LoginAttemptUtil {
    @Autowired
    LoginattemptService loginattemptService;
    public boolean isLocked(Integer userId){
        Loginattempt loginattempt = loginattemptService.selectByUserId(userId);
        if (loginattempt == null || loginattempt.getLockUntil() == null) {
            // 如果 Loginattempt 或其 lockUntil 属性为空，则认为不在锁定期内
            return false;
        }
        // 获取当前时间
        Date now = new Date();
        // 比较 lockUntil 和当前时间
        if (loginattempt.getLockUntil().after(now)) {
            long diffInMillies = Math.abs(loginattempt.getLockUntil().getTime() - now.getTime());
            long diffInHours = TimeUnit.HOURS.convert(diffInMillies, TimeUnit.MILLISECONDS);

            // 如果差值小于或等于 1 小时，则认为处于锁定期内
            return diffInHours <= 1;
        }
        // 如果 lockUntil 在当前时间之前，则不在锁定期内
        return false;
    }

    public boolean handleLoginError(Integer userId){
        Loginattempt loginattempt = loginattemptService.selectByUserId(userId);
            if (loginattempt == null){
                Loginattempt loginattempt1 = new Loginattempt();
                loginattempt1.setUserId(userId);
                loginattempt1.setLoginAttempts(1);
                loginattemptService.insert(loginattempt1);
                return true;
            }else {
                if (loginattempt.getLoginAttempts() == 5){
                    loginattempt.setLoginAttempts(1);
                    // 开启锁定
                    // 创建一个 Calendar 实例并设置为当前时间
                    Calendar calendar = Calendar.getInstance();
                    // 将时间增加1小时
                    calendar.add(Calendar.HOUR_OF_DAY, 1);
                    // 将增加后的时间设置为 lockUntil
                    loginattempt.setLockUntil(calendar.getTime());
                } else {
                    loginattempt.setLoginAttempts(loginattempt.getLoginAttempts() + 1);
                }
                loginattemptService.updateByPrimaryKey(loginattempt);
                return true;
            }
    }
}
